package agents;

import agents.tourguideagentbehaviours.FindTourForUserBehaviour;
import agents.tourguideagentbehaviours.SendTourToUserBehaviour;
import resource.UserProfile;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.core.behaviours.SequentialBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class TourGuideAgent extends Agent{
	private AID userAID;
	
	
	private UserProfile user;
	private String[] tour;
	
	public AID getUserAID() {
		return userAID;
	}
	
	public void setTour(String[] tour) {
		this.tour = tour;
	}

	public UserProfile getUser() {
		return user;
	}

	@Override
	protected void setup() {
		addBehaviour(new RegisterServiceBehaviour());
		addBehaviour(new ListenForMessageBehaviour());
	}
	
	class ListenForMessageBehaviour extends CyclicBehaviour{

		@Override
		public void action() {
			MessageTemplate template = MessageTemplate.MatchPerformative(ACLMessage.REQUEST);
			ACLMessage msg = myAgent.receive(template);
			if(msg != null){
				try{
					user = (UserProfile) msg.getContentObject();
					userAID = msg.getSender();
				}catch(UnreadableException e){
					throw new RuntimeException(e);
				}
				SequentialBehaviour sb = new SequentialBehaviour();
				sb.addSubBehaviour(new FindTourForUserBehaviour(TourGuideAgent.this));
				sb.addSubBehaviour(new SendTourToUserBehaviour(TourGuideAgent.this));
				myAgent.addBehaviour(sb);
			}
			else{
				block();
			}			
		}
	}
	
	class RegisterServiceBehaviour extends OneShotBehaviour{

		@Override
		public void action() {
			DFAgentDescription dfd = new DFAgentDescription();
	        dfd.setName(myAgent.getAID());
	        
	        ServiceDescription service = new ServiceDescription();
	        service.setName("tour");
	        service.setType("get tour");
	        service.addProperties(new Property("Namn", "Tour Guide"));
	        dfd.addServices(service);
	        try {
				DFService.register(myAgent, dfd);
			} catch (FIPAException e) {
				throw new RuntimeException(e);
			}
		}
	}

	public String[] getTour() {
		return tour;
	}
}
